package com.pkk.spring.cloud.service.gateway.util;

import java.util.Map;
import java.util.Objects;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;

/**
 * bean注册工具类
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-01-25 18:29
 **/
public class BeanRegistrationUtil {

  /**
   * 注册bean当bean不存在的时候
   *
   * @return boolean
   * @Param registry
   * @Param beanName
   * @Param beanClass
   * @author peikunkun
   * @date 2021/1/26 0026 上午 10:27
   * @since
   */
  public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
      Class<?> beanClass) {
    return registerBeanDefinitionIfNotExists(registry, beanName, beanClass, null);
  }


  /**
   * 注册bean当bean不存在的时候
   *
   * @return boolean
   * @Param registry
   * @Param beanName
   * @Param beanClass
   * @Param extraPropertyValues:注入扩展属性
   * @author peikunkun
   * @date 2021/1/26 0026 上午 10:27
   * @since
   */
  public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
      Class<?> beanClass, Map<String, Object> extraPropertyValues) {
    if (registry.containsBeanDefinition(beanName)) {
      return false;
    }

    String[] candidates = registry.getBeanDefinitionNames();
    for (String candidate : candidates) {
      BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
      if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {
        return false;
      }
    }

    BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();
    if (extraPropertyValues != null) {
      for (Map.Entry<String, Object> entry : extraPropertyValues.entrySet()) {
        beanDefinition.getPropertyValues().add(entry.getKey(), entry.getValue());
      }
    }

    registry.registerBeanDefinition(beanName, beanDefinition);
    return true;
  }


  public static BeanDefinition getBeanDefinition(BeanDefinitionRegistry registry, String beanName) {
    return registry.getBeanDefinition(beanName);
  }


}
